import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/generated/json/base/json_convert_content.dart';
import 'package:library_base/entities/in_order_page_goods_details_entity.dart';
import 'package:library_base/entities/location_entity.dart';
import 'package:library_base/entities/reason_entity.dart';
import 'package:library_base/ext/bool_ext.dart';
import 'package:library_base/ext/double_ext.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/network/http_util.dart';
import 'package:library_base/network/transform/fb_parse_transform.dart';
import 'package:library_base/res/decoration.dart';
import 'package:library_base/res/dividing_line.dart';
import 'package:library_base/res/edge.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/res/widget_generator.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/num_util.dart';
import 'package:library_base/utils/picker/time_picker.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/widget_generate_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:library_base/utils/get_util.dart';

import '../../utils/sp_util.dart';

class CreateWmsNoSingleDialog extends StatefulWidget {
  const CreateWmsNoSingleDialog({
    Key? key,
  }) : super(key: key);

  @override
  State<CreateWmsNoSingleDialog> createState() =>
      _CreateWmsNoSingleDialogState();
}

class _CreateWmsNoSingleDialogState extends State<CreateWmsNoSingleDialog> {
  var loginEnabled = false;

  late String id;

  late String goodsCode;

  late String serviceUnit;

  late String productName;

  late double stockInCount;

  late double stockInWeight;

  late String warehouseId;

  String? locationId;

  String? locationName;

  late int position;

  late Function(
      int position,
      List<InOrderPageGoodsDetailsEntity> listDetails,
      String locationId,
      String locationName,
      String? differenceReason,
      double stockInCount,
      double stockInWeight,
  ) updatePosition;

  late List<InOrderPageGoodsDetailsEntity> list;

  ///商品条码
  LocationEntity? goodsLocation;

  ReasonEntity? reason;

  TextEditingController goodsCountController = TextEditingController();
  FocusNode goodsCountFocusNode = FocusNode();

  TextEditingController goodsWeightController = TextEditingController();
  FocusNode goodsWeightFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    goodsLocation = Get.arguments['goodsLocation'];
    id = Get.arguments['stockInId'];
    goodsCode = Get.arguments['goodsCode'];
    locationId = Get.arguments['locationId'];
    locationName = Get.arguments['locationName'];
    updatePosition = Get.arguments['updatePosition'];
    list = Get.arguments['goodsDetails'];
    stockInCount = Get.arguments['stockInCount'];
    stockInWeight = Get.arguments['stockInWeight'];
    position = Get.arguments['position'];
    productName = Get.arguments['productName'];
    warehouseId = Get.arguments['warehouseId'];
    serviceUnit = Get.arguments['serviceUnit'];
    if (locationName != null && locationId != null) {
      goodsLocation = LocationEntity();
      goodsLocation!.locationName = locationName!;
      goodsLocation!.id = locationId!;
    }

    goodsCountController.text = stockInCount > 0 ? stockInCount.toString() : '';
    goodsWeightController.text = stockInWeight > 0.0 ? stockInWeight.remoteUnitTransitionLocalUnitStr(serviceUnit) : '';

    loginEnabled = isCanSubmit();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
          onWillPop: () {
            GetHelper.back();
            return Future.value(false);
          },
          child: GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              padding: const EdgeInsets.only(bottom: 50),
              width: double.infinity,
              color: Colors.transparent,
              alignment: Alignment.center,
              height: double.infinity,
              child: Row(
                children: [
                  SizedBox(width: 0.06.sw),
                  Expanded(
                    child: Container(
                      decoration: rs8,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            height: 95.w,
                            width: double.infinity,
                            child: Stack(
                              children: [
                                Container(
                                    alignment: Alignment.center,
                                    child: Text(MultiLanguage.locationEntry.tr,
                                        style: normalTextColor34)),
                                Positioned(
                                  top: 10.w,
                                  right: 0,
                                  child: GestureDetector(
                                    onTap: () => Get.back(),
                                    child: Padding(
                                        padding: edgeAll24,
                                        child: LocalImage('common_close',
                                            package: Constant.packLib(),
                                            width: 26.w,
                                            height: 26.w)),
                                  ),
                                )
                              ],
                            ),
                          ),
                          line1,
                          Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              gapH24,
                              Row(children: [
                                Expanded(
                                    flex: 2,
                                    child: Text(
                                      MultiLanguage.productName.tr,
                                      style: normalTextColor28,
                                      textAlign: TextAlign.end,
                                    )),
                                gapW24,
                                Expanded(
                                    flex: 7,
                                    child: Text(
                                      productName,
                                      style: normalTextColor28,
                                    )),
                              ]),
                              gapH18,
                              _buildInputItem(
                                title: MultiLanguage.commodityQuantity.tr,
                                hint: MultiLanguage.pleaseInputQuantity.tr,
                                controller: goodsCountController,
                                focusNode: goodsCountFocusNode,
                                onChanged: _countChange,
                              ),
                              gapH18,
                              _buildInputItem(
                                title: MultiLanguage.weightGoods.tr,
                                hint: "${MultiLanguage.pleaseInputWeight.tr}${SPUtil.isJin.unitStrZhWithBracket()}",
                                controller: goodsWeightController,
                                focusNode: goodsWeightFocusNode,
                                onChanged: _weightChange,
                              ),
                              Visibility(
                                  visible: Constant.isShowSeat,
                                  child: gapH18),
                              Visibility(
                                  visible: Constant.isShowSeat,
                                  child: buildItem(
                                      onTap: setGoodsLocation,
                                      title: MultiLanguage.goodsLocation.tr,
                                      hint: MultiLanguage
                                          .pleaseSelectAWarehouseLocation.tr,
                                      content: goodsLocation != null
                                          ? goodsLocation!.locationName
                                          : '')),
                              gapH18,
                              buildItem(
                                  onTap: difference,
                                  title: MultiLanguage.causesOfDifferences.tr,
                                  hint: MultiLanguage.pleaseSelectDifference.tr,
                                  content: reason != null ? reason!.label : ''),
                              gapH24,
                            ],
                          ),
                          line1,
                          GradientButton(
                            ThemeUtil.getTheme(),
                            width: double.infinity,
                            height: 77.r,
                            margin: edgeV36H24 as EdgeInsets,
                            text: MultiLanguage.determine.tr,
                            onPressed: loginEnabled ? determine : null,
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(width: 0.06.sw),
                ],
              ),
            ),
          )),
    );
  }

  buildItem(
      {GestureTapCallback? onTap,
      required String title,
      required String hint,
      String? content}) {
    return Row(children: [
      Expanded(
          flex: 2,
          child:
              Text(title, style: normalTextColor28, textAlign: TextAlign.end)),
      gapW24,
      Expanded(
          flex: 7,
          child: GestureDetector(
            onTap: onTap,
            child: Container(
                padding: edgeAll24,
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(30.0)),
                    border: Border.all(
                        color: ThemeUtil.getTheme().secondaryTextColor(),
                        width: 0.7)),
                child: Row(children: [
                  Expanded(
                      child: Text(
                          content == null || content.isEmpty ? hint : content,
                          style: content == null || content.isEmpty
                              ? TextStyles.textSecondary28
                              : normalTextColor28)),
                  LocalImage('common_grey_rightward_arrow',
                      package: Constant.packLib(), width: 20.w, height: 20.w),
                ])),
          )),
      gapW24,
    ]);
  }

  _buildInputItem({
    required String title,
    required String hint,
    TextEditingController? controller,
    FocusNode? focusNode,
    ValueChanged<String>? onChanged,
  }) {
    return Row(children: [
      Expanded(
          flex: 2,
          child:
              Text(title, style: normalTextColor28, textAlign: TextAlign.end)),
      gapW24,
      Expanded(
          flex: 7,
          child: buildInput(
            padding: edgeAll24,
            hintText: hint,
            controller: controller,
            focusNode: focusNode,
            textAlign: TextAlign.start,
            margin: const EdgeInsets.all(0),
            onChanged: onChanged,
          )),
      gapW24,
    ]);
  }

  determine() {
    var map = {};

    List<dynamic> goodsDetails = [];
    for (int i = 0; i < list.length; i++) {
      goodsDetails.add({
        'goodsBarCode': '',
        'weight': list[i].stockInWeight,
      });
    }
    map['id'] = id;
    var stockInWeight = double.parse(goodsWeightController.text).numAsUnitSubmit();
    map['detail'] = {
      'goodsCode': goodsCode,
      'stockInCount': double.parse(goodsCountController.text),
      'stockInWeight': stockInWeight,
      'locationId': goodsLocation!.id,
      'differenceReason': reason != null ? reason!.value : null,
      'goodsDetails': goodsDetails,
    };
    FBHttpUtil.post<Map>(context, Apis.STOCK_IN_RECORDS,
        params: map,
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result)).then((value) {
      if (value['code'] == HttpConfig.successCode) {
        String? temporaryDifferenceReason;
        if (reason != null) {
          temporaryDifferenceReason = reason!.label;
        }
        updatePosition(
            position,
            list,
            goodsLocation!.id,
            goodsLocation!.locationName,
            temporaryDifferenceReason,
            double.parse(goodsCountController.text),
            stockInWeight
        );
        GetHelper.back();
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  setGoodsLocation() {
    FBHttpUtil.get<Map>(context, Apis.GET_BY_WAREHOUSEID,
        params: {"warehouseId":warehouseId},
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result)).then((value) {
      if (value['code'] == HttpConfig.successCode) {
        List<LocationEntity> locationEntities =
            jsonConvert.convertList<LocationEntity>(value['data']);
        if (locationId != null && goodsLocation == null) {
          goodsLocation = locationEntities
              .firstWhere((element) => locationId == element.id);
        }
        Get.toNamed(Routers.LOCATION_PAGE, arguments: {
          'Buyer': locationEntities,
          'SelectedBuyer': goodsLocation,
          'callback': updateUi
        });
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  updateUi(LocationEntity locationEntity) {
    goodsLocation = locationEntity;
    loginEnabled = isCanSubmit();
    setState(() {});
  }

  difference() {
    FBHttpUtil.get<Map>(context, Apis.LIST_ALL_SIMPLE,
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result)
    ).then((value) {
      if (value['code'] == HttpConfig.successCode) {
        List<ReasonEntity> reasons = jsonConvert.convertList<ReasonEntity>(value['data']);
        var newReasons = reasons
            .where((element) => element.dictType == "scm_stock_in_difference_reason")
            .toList();
        singlePicker(context,
            showTitleBar: true,
            title: Text(
              MultiLanguage.pleaseSelectDifference.tr,
              style: normalTextColor34,
              textAlign: TextAlign.center,
            ),
            selectData: reason ?? newReasons[0],
            data: newReasons, onConfirm: (var data, int position) {
          reason = data;
          loginEnabled = isCanSubmit();
          setState(() {});
        });
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  ///判断是否自家的服务器标准的json格式,默认是有code和data即可
  bool isStandardJson(Map<dynamic, dynamic> data) {
    return data.containsKey('code') &&
        data.containsKey('data') &&
        data.containsKey('msg');
  }

  ///计算采购金额和重量
  void _countChange(String value) {
    loginEnabled = isCanSubmit();
  }

  ///计算采购金额和重量
  void _weightChange(String value) {
    loginEnabled = isCanSubmit();
  }

  bool isCanSubmit() {
    if (!NumUtil.isNumber(goodsCountController.text)) {
      return false;
    } else {
      if (double.parse(goodsCountController.text) <= 0.0) {
        return false;
      }
    }

    if (!NumUtil.isNumber(goodsWeightController.text)) {
      return false;
    } else {
      if (double.parse(goodsWeightController.text) <= 0.0) {
        return false;
      }
    }

    if (goodsLocation == null) {
      return false;
    }
    return true;
  }
}
